package com.tszs.Controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.tszs.AlipayUtils.AlipayConfig;
import com.tszs.biz.PersonalOrderBiz;
import com.tszs.entity.PersonalOrder;
import com.tszs.entity.PersonalOrderExample;
import com.tszs.entity.PersonalOrderExample.Criteria;
import com.tszs.util.CallBack;
import com.tszs.util.DateUtils;

/**
 * @类名：AliPayController
 * @类描述：支付宝支付
 * @author 王俊
 * @data 2019-04-05 11:02
 */
@Controller
public class AliPayController {

	@Autowired
	private PersonalOrderBiz personalOrderBiz;

	/***
	 * @方法名：alipayPayRequestModel
	 * @方法描述：支付宝支付
	 * @param response
	 * @throws IOException
	 * @throws AlipayApiException
	 */
	@RequestMapping("Alipay/alipayPayRequestModel")
	public void alipayPayRequestModel(HttpServletResponse response, HttpServletRequest request)
			throws IOException, AlipayApiException {

		AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
				AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key,
				"RSA2"); // 获得初始化的AlipayClient
		AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();// 创建API对应的request

		String orderId = new String(request.getParameter("id").getBytes("ISO-8859-1"), "UTF-8");

		PersonalOrderExample orderExample = new PersonalOrderExample();
		Criteria criteria = orderExample.createCriteria();
		criteria.andPIdEqualTo(orderId);
		List<PersonalOrder> orders = personalOrderBiz.selectByExample(orderExample);

		// 取到订单
		PersonalOrder order = orders.get(0);
		// 商户订单号，商户网站订单系统中唯一订单号，必填
		String out_trade_no = order.getTradeno();
		// 付款金额，必填
		String total_amount = order.getTotalCommodityPrice();
		// 订单名称，必填
		String subject = new String("天祥瑞订单");

		alipayRequest.setReturnUrl(AlipayConfig.return_url);
		alipayRequest.setNotifyUrl(AlipayConfig.notify_url);// 在公共参数中设置回跳和通知地址
		alipayRequest
				.setBizContent("{" + " \"out_trade_no\":\"" + out_trade_no + "\"," + " \"total_amount\":" + total_amount
						+ "," + " \"subject\":\"" + subject + "\"," + " \"product_code\":\"QUICK_WAP_PAY\"" + " }");// 填充业务参数
		String form = "";
		try {
			form = alipayClient.pageExecute(alipayRequest).getBody(); // 调用SDK生成表单
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}

		new CallBack().yes(response, form, "1");
	}

	/***
	 * @方法名：OrderInquiry
	 * @方法描述：支付宝支付订单退款· @param response
	 * @throws IOException
	 * @throws AlipayApiException
	 */
	@RequestMapping("Alipay/refund")
	public void refund(HttpServletResponse response) throws IOException, AlipayApiException {
		AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
				AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key,
				"RSA2");
		AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
		request.setBizContent("{" + " \"out_trade_no\":\"asdas15d1asfsa3f1safa\"," + " \"refund_amount\":\"0.01\","
				+ " \"refund_reason\":\"正常退款\"" + " }");// 设置业务参数
		AlipayTradeRefundResponse response2 = alipayClient.execute(request);
		System.out.println(response2.getBody());
		if (response2.isSuccess()) {
			System.out.println("退款成功");
		} else {
			System.out.println("退款失败");
		}
	}

	/***
	 * 服务器异步接受请求
	 * @author MRC
	 * @date 2019年5月29日下午5:07:05
	 * @param response
	 * @throws Exception 
	 */
	@RequestMapping("notify_url")
	public void notify(HttpServletResponse response,HttpServletRequest request) throws Exception{
		
		//获取支付宝POST过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
			//商户订单号

			String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
			//支付宝交易号

			String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

			//交易状态
			String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

			//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
			//计算得出通知验证结果
			//boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
			boolean verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, "RSA2");
			
			if(verify_result){//验证成功
				//////////////////////////////////////////////////////////////////////////////////////////
				//请在这里加上商户的业务逻辑程序代码
				//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
				if(trade_status.equals("TRADE_FINISHED")){
					//判断该笔订单是否在商户网站中已经做过处理
						//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
						//请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
						//如果有做过处理，不执行商户的业务程序
						
					//注意：
					//如果签约的是可退款协议，退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
					//如果没有签约可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
				} else if (trade_status.equals("TRADE_SUCCESS")){
					//修改订单状态
					PersonalOrder orderUpdate = new PersonalOrder();
					orderUpdate.setTradeno(out_trade_no);
					orderUpdate.setOutTradeNo(trade_no);
					orderUpdate.setpStatus("1");//在线支付
					orderUpdate.setpStatic("1");//购物车变成订单
					orderUpdate.setPayStatic("1");// 已支付
					orderUpdate.setRoutinStatus("1");//待发货
					orderUpdate.setPayMethod("2");//支付宝支付
					orderUpdate.setUpdatetime(DateUtils.getNowDateString());
					personalOrderBiz.updateOrderTradeSuccess(orderUpdate);
					
				}
				//////////////////////////////////////////////////////////////////////////////////////////
			}else{//验证失败
			}
	}
}